from django import forms
from django.http import HttpResponse
from django.shortcuts import render, redirect

from app01 import models
from app01.utils.bootstrap import BootstrapForm
from app01.utils.pagination import pagination
from app01.utils.encrypt import md5
from app01.utils.get_mage import check_code


class LoginForm(BootstrapForm):
    username = forms.CharField(
        label='工号', max_length=32,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入工号'}))
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入密码'},
                                   render_value=True))

    code = forms.CharField(
        label='验证码',
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入验证码'}),
        required=True,
    )

class ChangePasswordForm(BootstrapForm):
    old_password = forms.CharField(
        label='旧密码',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入旧密码'},
                                   render_value=True))
    new_password = forms.CharField(
        label='新密码',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入新密码'},
                                   render_value=True))
    re_password = forms.CharField(
        label='确认密码',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请再次输入新密码'},
                                   render_value=True))


class RegisterForm(BootstrapForm):
    staff_num = forms.CharField(
        label='工号', max_length=32,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入工号'}))

    name = forms.CharField(
        label='姓名', max_length=32,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入姓名'}))

    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入密码'},
                                   render_value=True))
    re_password = forms.CharField(
        label='确认密码',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请再次输入密码'},
                                   render_value=True))

    def clean_staff_num(self):
        staff_num = self.cleaned_data.get('staff_num')
        if models.StaffInfo.objects.filter(staff_num=staff_num).first():
            self.add_error('staff_num', '工号已存在')
        return staff_num

    def clean(self):
        password = self.cleaned_data.get('password')
        re_password = self.cleaned_data.get('re_password')
        if password and re_password:
            if password != re_password:
                self.add_error('re_password', '两次密码不一致')
        return self.cleaned_data



def clean_password(self):
    password = self.cleaned_data.get('password')
    # print('1', md5(password))
    return password


def login(request):
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'login.html', {'form': form})

    form = LoginForm(request.POST)
    if form.is_valid():
        user_input_code = form.cleaned_data['code']
        session_code = request.session.get('image_code', '')
        if user_input_code.upper() != session_code.upper():
            form.add_error('code', '验证码错误')
            return render(request, 'login.html', {'form': form})

        # 切记：不能直接使用form.cleaned_data.get('username')
        # form.cleaned_data的值是一个字典，而不是一个字符串，需要和数据库中字段一致
        # 所以需要使用form.cleaned_data.get('username')
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        user = models.StaffInfo.objects.filter(staff_num=username, password=clean_password(form)).first()
        print(user)
        if not user:
            form.add_error('password', '用户名或密码错误')
            return render(request, 'login.html', {'form': form})
        request.session['info'] = {'id': user.staff_num, 'name': user.name}
        # seeion可以保存7天
        request.session.set_expiry(7 * 24 * 60 * 60)
        return redirect('/customer/list/')
    return render(request, 'login.html', {'form': form})


def logout(request):
    """"退出登录"""
    request.session.flush()
    return redirect('/login/')


from io import BytesIO


def image_code(request):
    """生成图片验证码"""
    img, code_string = check_code()

    request.session['image_code'] = code_string
    # 设置验证码的过期时间
    request.session.set_expiry(60)

    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def register(request):
    if request.method == 'GET':
        form = RegisterForm()
        return render(request, 'register.html', {'form': form})

    form = RegisterForm(request.POST)
    if form.is_valid():
        form.cleaned_data.pop('re_password')
        models.StaffInfo.objects.create(**form.cleaned_data)
        return redirect('/login/')

    return render(request, 'register.html', {'form': form})


def change_password(request):
    if request.method == 'GET':
        form = ChangePasswordForm()
        return render(request, 'change_password.html', {'form': form})

    form = ChangePasswordForm(request.POST)
    if form.is_valid():
        old_password = form.cleaned_data.get('old_password')
        new_password = form.cleaned_data.get('new_password')
        re_password = form.cleaned_data.get('re_password')
        user = models.StaffInfo.objects.filter(staff_num=request.session['info']['id'], password=old_password).first()
        if not user:
            form.add_error('old_password', '原密码错误')
            return render(request, 'change_password.html', {'form': form})
        if new_password != re_password:
            form.add_error('re_password', '两次密码不一致')
            return render(request, 'change_password.html', {'form': form})
        user.password = new_password
        user.save()
        return redirect('/login/')